var ProxyPool = require("./ProxyPool.js"),
    ProxyInfo = require("../common/ProxyInfo.js"),
    Util = require("../util/util.js"),
    request = require("request"),
    fs = require("fs"),
    App = require("../common/App.js");

module.exports = new SyncProxy();

function SyncProxy(){
    //单例模式
    if(typeof arguments.callee.instance === "object"){
        return arguments.callee.instance;
    }

    arguments.callee.instance = this;
}

SyncProxy.prototype.start = function(){
    var apiUrl = App.config.SyncProxyUrl;
    request.get(apiUrl,function(err, res, body){
        if(!err && res.statusCode==200){

            body = Util.replaceAll(body,"\r","\n");
            body = Util.replaceAll(body,"\n\n","\n");
            var iplist = body.split("\n");
            var len = iplist.length;
            for(var i=0;i<len;i++){
                var ipArr = iplist[i].split(":");
                if(ipArr.length==2){
                    var proxy = new ProxyInfo();
                    proxy.host = ipArr[0];
                    proxy.port = ipArr[1];
                    ProxyPool.push(proxy);
                }
            }
        }else{
            console.log("SyncProxy fail "+err);
        }
    });
}

/**
 * 载入重启服务前的有效代理
 */
SyncProxy.prototype.loadProxy = function(){
    var savePath = App.config.proxy_tmp_save;
    if(fs.existsSync(savePath)){
        try{
            var proxyJsonStr = fs.readFileSync(savePath);
            var proxyJson = JSON.parse(proxyJsonStr);
            var len = proxyJson.length;
            for(var i=0;i<len;i++){
                var p = proxyJson[i];
                if(p.host!=undefined){
                    var proxy = new ProxyInfo(p);
                    ProxyPool.push(proxy);
                }
            }
        }catch (e){
        }
    }
}